<?php


namespace app\api\controller;


use app\BaseController;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use app\common\model\User;
class WxLogin extends BaseController
{
    protected $code;
    protected $wxAppId;
    protected $wxAppSecret;
    protected $wxLoginUrl;
    protected $ip;
    protected $pid;
    protected $invite_silver=10;
    protected $user;
    protected $device;

    public function login()
    {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        // 判断是否是iOS设备（iPhone/iPad）
        $this->device=$userAgent;
        $accessToken = input('access_token');
        $openId = input('openid');
        $invite_code = input('invite_code');

        // 获取用户信息
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
        $userInfoResponse = curl_get($userInfoUrl);
        $userInfo = json_decode($userInfoResponse, true);
        if (isset($userInfo['errcode'])) {
            return show(0,'登录失败,请重试');
        }

        if ($invite_code){
            $p=\think\facade\Db::name('user')->where('invite_code',$invite_code)->find();
            if ($p){
                $pid=$p['id'];
            }else{
                $pid=0;
            }
        }else{
            $pid=0;
            $p=[];
        }
        //判断手机号是否为新增还是登录
        $user = User::getByUnionID($userInfo['unionid']);
        if ($user) {
            $uid = $user['id'];
        } else {
            $uid = $this->newUser($userInfo,$pid,$p);
            if ($uid == false) {
                return false;
            }
            $user['is_vip']=2;
        }
        //生成保存的数据
        $cachedValue = $this->prepareCachedValue($uid,$user['is_vip']);
        //保存缓存
        $token = $this->saveToCache($cachedValue);
        $data['token']=$token;
        $data['is_vip']=$user['is_vip'];
        return show(1,'',$data);
    }
    /**\
     * @param $openid
     * @return mixed
     * 去创建新用户
     */
    private function newUser($userInfo,$pid,$p=[])
    {
        $abc = city($this->ip);
        $device = get_device($this->device);
        \think\facade\Db::startTrans();
        try {
            //生成邀请码
            $invite_code=get_invite_code();
            $user = \think\facade\Db::name('user')
                ->insertGetId([
                    'nickname' => $userInfo['nickname'],
                    'unionid' => $userInfo['unionid'],
                    'openid' => $userInfo['openid'],
                    'create_time' => time(),
                    'ip' => $this->ip,
                    'country' => $abc['nation'],
                    'province' => $abc['region'],
                    'city' => $abc['city'],
                    'pid'=>$pid,
                    'is_vip'=>2,
                    'invite_code'=>$invite_code,
                    'vip_end_time'=>time()+604800,
                    'device_type'=>$device,
                    'register_type'=>"微信",
                ]);
            //给上级增加邀请记录
            if ($pid>0){
                //增加邀请记录
                \think\facade\Db::name('invite_record')
                    ->insert(['pid'=>$pid,'uid'=>$user,'create_time'=>time(),'update_time'=>time()]);
                //给第一次的上级赠送vip
                $one=\think\facade\Db::name('invite_record')
                    ->where(['pid'=>$pid])
                    ->count();
                if ($one==1){
                    $data[]=[
                        'user_id'=>$pid,
                        'day'=>7,
                        'create_time'=>time(),
                        'type'=>2,
                    ];
                    //再给增加vip时间
                    if ($p['is_vip']==1){
                        \think\facade\Db::name('user')
                            ->where('id',$p['id'])
                            ->update(['is_vip'=>2,'vip_end_time'=>time()+604800]);
                    }else{
                        \think\facade\Db::name('user')
                            ->where('id',$p['id'])
                            ->update(['is_vip'=>2,'vip_end_time'=>$p['vip_end_time']+604800]);
                    }
                }
            }
            //如果是第一个赠送vip奖励
            $data[]=[
                'user_id'=>$user,
                'day'=>7,
                'create_time'=>time(),
                'type'=>1,
            ];
            \think\facade\Db::name('user_vip_record')
                ->insertAll($data);
            \think\facade\Db::commit();
            return $user;
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return false;
        }
    }

    /**\
     * @param $wxResult
     * @param $uid
     * @return mixed
     * 写入缓存的数据
     */
    private function prepareCachedValue($uid,$is_vip)
    {
        $cachedValue['uid'] = $uid;
        $cachedValue['is_vip'] = $is_vip;
        return $cachedValue;
    }

    //写入缓存
    private function saveToCache($cachedValue)
    {
        //32个字符组成一组随机字符串
        $randChars = md5(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT));
        //用三组字符串,进行md5加密
        Cache::set($randChars,serialize($cachedValue),2592000);
        return $randChars;
    }

}